from django.utils import timezone
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url


def _clear_cache():
    now = timezone.now()
    CaptchaStore.objects.all().filter(expiration__lt=now).delete()


def get_captcha(request):
    new_key = CaptchaStore.pick()
    response_data = {
        'key': new_key,
        'image_url': request.build_absolute_uri(location=captcha_image_url(new_key)),
    }
    return response_data


def validate_captcha(key, value):
    try:
        captcha = CaptchaStore.objects.get(response=value.lower(), hashkey=key)
        captcha.delete()
        _clear_cache()
    except CaptchaStore.DoesNotExist:
        _clear_cache()
        return False
    return True
